import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column } from './stores/definitions';
import DrawerFooter from '@/components/DrawerFooter';
import CouponInfoTable from './components/CouponInfoTable';

const tableId = uniqueId('tauTable-');

function Price({ activity, onCancel, modal: orderMode }) {
  const { priceCountStore: store } = useStore();
  const [data, setData] = useState([]);
  const [expandAll, setExpandAll] = useState(false);
  const [currentPage, setCurrentPage] = useState(0); // 默认页数
  const [pageSize, setPageSize] = useState(10); // 每页显示的数据数量

  useEffect(() => {
    setData(activity?.batchPriceInfos || []);
    return () => {
      store.orderStatus = '0';
    };
  }, []);

  useEffect(() => {
    if (orderMode[1]?.startsWith?.('toClose')) handleCancel();
  }, [orderMode]);

  if (!activity) return <></>;

  // 根据当前页码和每页数量获取当前页需要显示的数据
  const startIndex = currentPage * pageSize;
  const endIndex = startIndex + pageSize;
  const currentPageData = data.slice(startIndex, endIndex);

  // Modal窗口关闭回调
  const handleCancel = () => {
    onCancel?.();
  };

  return (
    <TauPage className="page-container">
      <Tab
        extra={<Button type="primary" onClick={() => setExpandAll(!expandAll)}>{expandAll ? t`合并全部` : t`展开全部`}</Button>}
      >
        <Tab.Item title={t`批次统计`} />
      </Tab>
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={currentPage}
          pageSize={pageSize}
          total={data.length}
          onFetch={({ page, size }) => {
            setCurrentPage(page);
            size && setPageSize(size);
          }}
          loading={store.loading}
          dataSource={currentPageData}
          expandedRowRender={(row) => (
            <CouponInfoTable
              customerPriceInfos={row.customerPriceInfos}
              batchId={row.batchId}
              batchName={row.batchName}
            />
          )}
          expandedRowIndent={[100, 100]}
          expandAll={expandAll}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i, currentPage, pageSize) },
            column('batchId', { width: 128 }),
            column('batchName', { width: 128 }),
            column('requestedPrice', { width: 128 }),
            column('distributionPrice', { width: 128 }),
            column('consumedPrice', { width: 128 }),
          ]}
        />
      </div>
      <DrawerFooter>
        <Button style={{ marginLeft: 8 }} onClick={() => handleCancel()}>{t`取消`}</Button>
      </DrawerFooter>
    </TauPage>
  );
}

export default observer(Price);
